package com.urtime.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;

import com.urtime.model.Event;
import com.urtime.model.User;
import com.urtime.util.Common;
import com.urtime.util.ErrorJson;
import com.urtime.util.HibernateUtil;
import com.urtime.util.UrTimeServerConfig;

public class UserDAO {
	static public boolean validateUsername(String username){
		if(username==null||username.isEmpty() || username.length()>UrTimeServerConfig.MAX_INFO_STRING)
			return false;
		if(username.matches("^[a-zA-Z_][a-zA-Z0-9_]+"))
			return true;
		return false;
	}
	static public boolean validatePassword(String pw){
		if(pw==null||pw.isEmpty() || pw.length()>UrTimeServerConfig.MAX_INFO_STRING)
			return false;
		return true;
	}
	static public int AddUser(String username, String origPassword){
		if(!validateUsername(username) || !validatePassword(origPassword)) 
			return ErrorJson.ERROR_PARAMS;
		String md5pw = Common.md5(origPassword);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        try{
	        session.beginTransaction();
	        
	        int cnt = session.createQuery("from User where username='"+username+"'").list().size();
	        if(cnt==0){
		        User user = new User();
		        user.setUsername(username);
		        user.setPassword(md5pw);
		        user.setRegisterTime(new Date());
		        session.save(user);
		        session.getTransaction().commit();	
		        return ErrorJson.ERROR_OK;
	        }
	        else{
	        	session.getTransaction().commit();	
	        	return ErrorJson.ERROR_USER_EXISTS;
	        }
        }catch(Exception e){
        	session.getTransaction().rollback();
        	//session.close();
        }
        return ErrorJson.ERROR_UNKNOWN;
        
	}
	
	static public List<User> queryUser(String hql){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        @SuppressWarnings("unchecked")
		List<User> result = session.createQuery("from User "+hql).list();
        session.getTransaction().commit();
        return result;
	}
	
	static public User getUserByID(int id){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		return (User)session.get(User.class, id);
	}
	
	static public void updateInfo(User u){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try{
			session.beginTransaction();
			session.update(u);
			session.getTransaction().commit();
		}catch(Exception e){
			session.getTransaction().rollback();
		}
	}
	

}
